From 6a2ba5cb7ec7a87a4c2b023f4f0ea61d19fc360a Mon Sep 17 00:00:00 2001 From: David Vrabel Date: Wed, 18 Jun 2014 17:12:51 +0100 Subject: [PATCH] libxl: add libxl__random_bytes() which fills a buffer with random bytes The random bytes are obtained from /dev/urandom and are suitable for almost all uses (except for generating long-lived secure keys). Documentation suggests that /dev/urandom is widely available on Unix-like systems (such FreeBSD and NetBSD). A public libxl_random_bytes() (or similar) could be trivially added, if this required in the future. Signed-off-by: David Vrabel Acked-by: Ian Campbell --- tools/libxl/libxl_internal.h | 2 ++ tools/libxl/libxl_utils.c | 22 ++++++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/tools/libxl/libxl_internal.h b/tools/libxl/libxl_internal.h index a0d4f241d4..a9343e8dce 100644 --- a/tools/libxl/libxl_internal.h +++ b/tools/libxl/libxl_internal.h @@ -3180,6 +3180,8 @@ int libxl__uint64_parse_json(libxl__gc *gc, const libxl__json_object *o, int libxl__string_parse_json(libxl__gc *gc, const libxl__json_object *o, char **p); +int libxl__random_bytes(libxl__gc *gc, uint8_t *buf, size_t len); + #endif /* diff --git a/tools/libxl/libxl_utils.c b/tools/libxl/libxl_utils.c index 16b734efd0..0001ab8f17 100644 --- a/tools/libxl/libxl_utils.c +++ b/tools/libxl/libxl_utils.c @@ -1013,6 +1013,28 @@ int libxl_domid_valid_guest(uint32_t domid) return domid > 0 && domid < DOMID_FIRST_RESERVED; } +/* + * Fill @buf with @len random bytes. + */ +int libxl__random_bytes(libxl__gc *gc, uint8_t *buf, size_t len) +{ + static const char *dev = "/dev/urandom"; + int fd; + int ret; + + fd = open(dev, O_RDONLY | O_CLOEXEC); + if (fd < 0) { + LOGE(ERROR, "failed to open \"%s\"", dev); + return ERROR_FAIL; + } + + ret = libxl_read_exactly(CTX, fd, buf, len, dev, NULL); + + close(fd); + + return ret; +} + /* * Local variables: * mode: C -- 2.30.2